package edu.stanford.hardon.Tabs;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Date;

import edu.stanford.hardon.DatabaseHelper;
import edu.stanford.hardon.R;
import edu.stanford.hardon.TravelCore;
import edu.stanford.hardon.TravelHard;
import edu.stanford.hardon.TravelHardConstants;
import edu.stanford.hardon.Media.MediaType;
import edu.stanford.hardon.Media.RichMedia;
import android.content.Context;
import android.graphics.PixelFormat;
import android.hardware.Camera;
import android.location.Location;
import android.media.MediaRecorder;
import android.os.AsyncTask;
import android.os.Environment;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.LinearLayout;

public class VideoTab extends GenericTab{

	//Camera specific variables
	private SurfaceView preview = null;
	private SurfaceHolder previewHolder=null;
	private Camera camera=null;
	private boolean usingCamera = false;
	private boolean inPreview=false;
	boolean freeFile;
	private int currentFreeFile;
	private boolean recording = false;
	private VideoRecorder recorder;

	
	public VideoTab(int Id, String Text, int iconResourceId, LinearLayout tabLayout, SurfaceView previewSurface, TravelHard th) {
		super(Id, Text, iconResourceId,tabLayout, th);

		recorder = new VideoRecorder();

		  //set up tab to contain a camera view thingy.
		currentFreeFile = 0;
        preview = previewSurface;
    	LayoutParams lp = preview.getLayoutParams();
		preview.setLayoutParams(lp);
        previewHolder=preview.getHolder();
		previewHolder.addCallback(surfaceCallback);
		previewHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
		
		Button captureButton = (Button) tabLayout.findViewById(R.id.capture_video);
		captureButton.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
            	if(!recording){
            		try {
        				if(!recording){
        					recording = true;
        					recorder.record();
        				} else {
        					recording = false;
        					recorder.stopRecording();
        				}
        			} catch (IOException e) {
        				// TODO Auto-generated catch block
        				e.printStackTrace();
        			}
            	}
            }
        });

	}

	@Override
	public void startTab() {
		if(camera == null){
			camera=Camera.open();
			camera.setParameters(camera.getParameters());
			try{
				camera.setPreviewDisplay(previewHolder);
				camera.setDisplayOrientation(90);
			}
			catch(IOException e){
				
			}
			camera.startPreview();
			usingCamera = true;
			inPreview = true;
			
		}
		
	}

	@Override
	public void stopTab() {
		// TODO Auto-generated method stub
		if(camera != null){
			camera.stopPreview();
			camera.release();
			camera=null;
			inPreview=false;
			usingCamera = false;
		}
	}
	
	  
    SurfaceHolder.Callback surfaceCallback=new SurfaceHolder.Callback() {
		public void surfaceCreated(SurfaceHolder holder) {
			if(usingCamera){
			try {
			
				camera.setPreviewDisplay(previewHolder);
			
				
			}
			catch (Throwable t) {
//				Log.e("PictureDemo-surfaceCallback",
//							"Exception in setPreviewDisplay()", t);
//				Toast
//					.makeText(TravelHard.this, t.getMessage(), Toast.LENGTH_LONG)
//					.show();
			}
			}
		}
		
		public void surfaceChanged(SurfaceHolder holder,
															 int format, int width,
															 int height) {
			if(camera != null && usingCamera){
				if(!inPreview){
					Camera.Parameters parameters=camera.getParameters();
			
					parameters.setPreviewSize(width, height);
					parameters.setPictureFormat(PixelFormat.JPEG);
				
					camera.setParameters(parameters);
				
					camera.startPreview();
					inPreview=true;
				}
			}
		}
		
		public void surfaceDestroyed(SurfaceHolder holder) {
			// no-op
		}
	};

	@Override
	public void setPaused() {
		if(usingCamera){
			if (inPreview) {
				camera.stopPreview();
			}
		
			camera.release();
			camera=null;
			inPreview=false;
			usingCamera = false;
		}
	}

	@Override
	public void setResumed() {
		if(camera == null){
			camera=Camera.open();
			camera.setParameters(camera.getParameters());
			try{
				camera.setPreviewDisplay(previewHolder);
			}
			catch(IOException e){
				
			}
			camera.startPreview();
			usingCamera = true;
			inPreview = true;
			
		}
		
	}
	
	public class VideoRecorder {

		private MediaRecorder recorder;
		private File videoFile;

		public VideoRecorder() {
		}

		/**
		 * Starts a new recording.
		 */
		public void record() throws IOException {

			recorder = new MediaRecorder();

			String state = android.os.Environment.getExternalStorageState();
			if(!state.equals(android.os.Environment.MEDIA_MOUNTED))  {
				throw new IOException("SD Card is not mounted.  It is " + state + ".");
			}

			//choose the file to write
			File video = null;
			boolean freeFile = false;
			int currentFreeFile = 0;

			while(!freeFile){
				video=new File(Environment.getExternalStorageDirectory(), "video" + currentFreeFile + ".mp4");

				if (video.exists()) currentFreeFile++;
				else freeFile = true;
			}

			this.videoFile = video;
			Log.i("AUDIO", video.getPath());

			Log.i("Debug", "d1");

			//camera.unlock();
			//recorder.setCamera(camera);
			
			
			recorder.setAudioSource(MediaRecorder.AudioSource.CAMCORDER);
			recorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);
			
			recorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
			
			recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
			
			recorder.setVideoEncoder(MediaRecorder.VideoEncoder.MPEG_4_SP);
			
			recorder.setVideoFrameRate(15);
			
			//recorder.setMaxDuration(100000);
			
            recorder.setVideoSize(preview.getWidth(), preview.getHeight());

			recorder.setPreviewDisplay(previewHolder.getSurface());
			
			recorder.setOutputFile(videoFile.getPath());

			Log.i("Debug", "d2");

			recorder.prepare();

			Log.i("Debug", "d3");

			recorder.start();

		}

		/**
		 * Stops a recording that has been previously started.
		 */
		public void stopRecording() throws IOException {
			recorder.stop();
			recorder.release();
			Date date = new Date();
			Double lat = 0.0, lng = 0.0, alt = 0.0;
			if(th.location != null) {
				lat = th.location.getLatitude();
				lng = th.location.getLongitude();
				alt = th.location.getAltitude();
			}	
//			RichMedia videoMedia = new RichMedia(null, TravelHardConstants.TRIP_ID, MediaType.PHOTO, lat, lng, alt, date, null, 0, VIDEO_PATH);
//			DatabaseHelper dbhh = TravelCore.getDBH();
//			dbhh.open();
//			dbhh.insert(videoMedia);
//			dbhh.close();
		}

	}


}
